<template>
  <a-card :bordered="false">
    <a-card :bordered="false" :body-style="{ padding: '0' }">
      <div class="salesCard">
        <a-card>
          <p><a href="https://spatialreference.org/ref/">Spatial Reference</a></p>
          <p><a href="https://epsg.org/search/by-name">Geodetic Parameters</a></p>
        </a-card>
        <a-tabs v-model="activeKey" size="large" :tab-bar-style="{ marginBottom: '24px', paddingLeft: '16px' }">
          <!-- <a-tab-pane v-for="pane in panes" :key="pane.key" :tab="pane.title">
                <a-table size="small" :columns="pane.columns" :data-source="pane.dataSource" :scroll="{ x: 2500, y: 300 }" :pagination="pane.ipagination">
                </a-table>
            </a-tab-pane> -->
          <a-tab-pane key="inputType" tab="坐标输入">
            <a-card :bordered="false">
              <!-- <a-form>
                        <a-form-item
                        :label-col="{ span: 4 }"
                        :wrapper-col=" { span: 8 }"
                        label="坐标X"
                        >
                        <a-input

                            placeholder="Please input your name"
                        />
                        </a-form-item>
                    </a-form> -->
              <a-form :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-row>
                  <a-col :span="12">
                    <a-form-item label="X坐标">
                      <a-input v-model="form.X" placeholder="请输入X坐标" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="Y坐标">
                      <a-input v-model="form.Y" placeholder="请输入Y坐标" />
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="12">
                    <a-form-item label="经度坐标">
                      <a-input v-model="form.lng" placeholder="请输入经度坐标" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="纬度坐标">
                      <a-input v-model="form.lat" placeholder="请输入纬度坐标" />
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="12">
                    <a-form-item label="原坐标系">
                      <a-select v-model="form.SourcePrj" placeholder="请选择原坐标系">
                        <a-select-option value="cgcs30007"> 自定义平面坐标系(大地2000经线118.5) </a-select-option>
                        <a-select-option value="webMercator"> 墨卡托平面坐标系 </a-select-option>
                        <a-select-option value="cgcs2000"> 大地2000地理坐标系 </a-select-option>
                        <a-select-option value="wgs84"> WGS84世界地理坐标系 </a-select-option>
                        <a-select-option value="other"> 其他坐标系 </a-select-option>
                      </a-select>
                      <a-input
                        v-if="form.SourcePrj == 'other'"
                        v-model="form.otherSrcPrj"
                        placeholder="请输入其他坐标系"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="目标坐标系">
                      <a-select v-model="form.TargetPrj" placeholder="请选择目标坐标系">
                        <a-select-option value="cgcs30007"> 自定义平面坐标系(大地2000经线118.5) </a-select-option>
                        <a-select-option value="webMercator"> 墨卡托平面坐标系 </a-select-option>
                        <a-select-option value="cgcs2000"> 大地2000地理坐标系 </a-select-option>
                        <a-select-option value="wgs84"> WGS84世界地理坐标系 </a-select-option>
                        <a-select-option value="other"> 其他坐标系 </a-select-option>
                      </a-select>
                      <a-input
                        v-if="form.TargetPrj == 'other'"
                        v-model="form.otherTarPrj"
                        placeholder="请输入其他坐标系"
                      />
                    </a-form-item>
                  </a-col>
                </a-row>

                <a-form-item :wrapper-col="{ span: 24, offset: 8 }">
                  <a-button type="primary" @click="onSubmit"> 转换 </a-button>
                  <a-button style="margin-left: 10px"> 重置 </a-button>
                </a-form-item>
              </a-form>
            </a-card>
          </a-tab-pane>
          <a-tab-pane key="importType" tab="坐标导入">
            <div class="table-operator">
              <a-button @click="handleImportXls" type="primary" icon="upload">导入</a-button>
              <!--  此处省略部分代码...... -->
              <j-import-modal ref="importModal" :url="getImportUrl()" @ok="importOk" v-model="panes"></j-import-modal>
              <a-button @click="handleExportXls" type="primary" icon="download">导出属性</a-button>
              <a-button @click="handleExportTestXls" type="primary" icon="download">导出校验结果</a-button>
              <!-- <a-button type="dashed" @click="tableOption">{{ (optionAlertShow && '关闭') || '开启' }} alert</a-button>
                <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
                    <a-menu slot="overlay">
                    <a-menu-item key="1"><a-icon type="delete" />删除</a-menu-item>
                    <a-menu-item key="2"><a-icon type="lock" />锁定</a-menu-item>
                    </a-menu>
                    <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /> </a-button>
                </a-dropdown> -->
            </div>
          </a-tab-pane>
          <a v-if="fileName && fileName.length > 0" slot="tabBarExtraContent">
            {{ fileName }}
          </a>
        </a-tabs>
      </div>
    </a-card>
    <!-- <a-card :bordered="false" :body-style="{padding: '0'}"  title="空间表">
      <div class="salesCard">
        <a-tabs v-model="activeKey" size="large" :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}">
          <a-tab-pane v-for="pane in panes" :key="pane.key" :tab="pane.title">

          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>     -->
  </a-card>
</template>

<script>
import * as XLSX from 'xlsx/xlsx.mjs'
import moment from 'moment'
import proj4 from 'proj4'
import { STable, Ellipsis } from '@/components'
import { getRoleList, getServiceList } from '@/api/manage'
import JImportModal from '@/components/jeecg/JImportModal.vue'
const statusMap = {
  0: {
    status: 'default',
    text: '关闭'
  },
  1: {
    status: 'processing',
    text: '运行中'
  },
  2: {
    status: 'success',
    text: '已上线'
  },
  3: {
    status: 'error',
    text: '异常'
  }
}
var wgs84 = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs  '
var cgcs2000 = '+proj=tmerc +lat_0=0 +lon_0=120 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs'
var webMercator =
  '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs'
var cgcs30007 = '+proj=tmerc +lat_0=0 +lon_0=118.5 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs'

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    JImportModal
  },
  data() {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      form: {
        X: undefined,
        Y: undefined,
        lng: undefined,
        lat: undefined,
        SourcePrj: undefined,
        TargetPrj: undefined,
        region: undefined,
        date1: undefined,
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      mdl: {},
      fileList: [],
      dataSources: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '#',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '规则编号',
          dataIndex: 'no'
        },
        {
          title: '描述',
          dataIndex: 'description',
          scopedSlots: { customRender: 'description' }
        },
        {
          title: '服务调用次数',
          dataIndex: 'callNo',
          sorter: true,
          needTotal: true,
          customRender: (text) => text + ' 次'
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '更新时间',
          dataIndex: 'updatedAt',
          sorter: true
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      filters: [
        {
          text: '空',
          value: 1
        },
        {
          text: '经纬度正确',
          value: 0
        }
      ],
      onFilter: (value, record) => {
        // eslint-disable-next-line no-unused-expressions
        record.lnglatErr === value
      },
      // 加载数据方法 必须为 Promise 对象
      // loadData: parameter => {
      //   console.log('loadData.parameter', parameter)
      //   return getServiceList(Object.assign(parameter, this.queryParam))
      //     .then(res => {
      //       return res.result
      //     })
      // },
      selectedRowKeys: [],
      selectedRows: [],
      // custom table alert & rowSelection
      options: {
        alert: {
          show: true,
          clear: () => {
            this.selectedRowKeys = []
          }
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: false,
      panes: [
        { title: '坐标输入', content: 'Content of Tab 1', key: 'inputType' },
        { title: '坐标导入', content: 'Content of Tab 2', key: 'importType' }
      ],
      activeKey: 'inputType',
      fileName: null
    }
  },
  watch: {
    panes: {
      deep: true,
      immediate: false,
      handler(val) {
        console.log(this.panes)
        this.activeKey = this.panes[0].key
      }
    }
  },
  // filters: {
  //   statusFilter (type) {
  //     return statusMap[type].text
  //   },
  //   statusTypeFilter (type) {
  //     return statusMap[type].status
  //   }
  // },
  created() {
    this.tableOption()
    getRoleList({ t: new Date() })
  },
  methods: {
    onSubmit() {
      console.log('submit!', this.form)
      console.log(proj4(cgcs30007, wgs84, [Number(this.form.X), Number(this.form.Y)]))
      const lnglat = proj4(cgcs30007, wgs84, [Number(this.form.X), Number(this.form.Y)])
      this.form.lng = lnglat[0]
      this.form.lat = lnglat[1]
    },
    tableOption() {
      if (!this.optionAlertShow) {
        this.options = {
          alert: {
            show: true,
            clear: () => {
              this.selectedRowKeys = []
            }
          },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange,
            getCheckboxProps: (record) => ({
              props: {
                disabled: record.no === 'No 2', // Column configuration not to be checked
                name: record.no
              }
            })
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },

    handleSub(record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    handleImportXls() {
      this.$refs.importModal.show()
    },
    getImportUrl() {
      return '你自己处理上传业务的后台地址'
    },
    importOk(fileName) {
      this.fileName = fileName
      // console.log(this.panes)
      // if(this.panes.length > 0 ){
      //   this.activeKey = this.panes[0].key
      // }
      // this.loadData(1)
    },
    handleExportXls() {
      // 创建工作簿
      const wb = XLSX.utils.book_new()
      const obj = {}
      this.panes.map((item) => {
        // 将数据写入表格中
        const sheet = XLSX.utils.json_to_sheet(item.dataSource)
        // var range = XLSX.utils.decode_range(sheet['!ref']);
        // let appendCol = XLSX.utils.encode_col(range.e.c + 1);
        // XLSX.utils.sheet_set_array_formula(sheet, appendCol + "2:" + appendCol + range.e.r, "A1:A3*B1:B3");
        // var range = XLSX.utils.decode_range(ws['!ref']);
        // for (R = r.s.r; R <= r.e.r; ++R);

        // 将工作表放入工作簿中
        XLSX.utils.book_append_sheet(wb, sheet, item.name)
      })
      var l = null
      if (wb.SheetNames.includes('TZ_GXDSX')) {
        const gxd_range = XLSX.utils.decode_range(wb.Sheets['TZ_GXDSX']['!ref'])
        l = XLSX.utils.encode_col(gxd_range.e.c)
        var xNum, yNum
        for (let C = gxd_range.s.c; C <= gxd_range.e.c; ++C) {
          const coord = XLSX.utils.encode_cell({ r: 0, c: C })
          const cell = wb.Sheets['TZ_GXDSX'][coord]
          if (cell.v == 'X') {
            xNum = C + 1
          }
          if (cell.v == 'Y') {
            yNum = C + 1
          }
        }
      }

      if (l && wb.SheetNames.includes('TZ_GXSX')) {
        const GXSX_r = XLSX.utils.decode_range(wb.Sheets['TZ_GXSX']['!ref'])
        var s_poi_c, x_c, y_c, e_poi_c, x_c_1, y_c_1
        for (let C = GXSX_r.s.c; C <= GXSX_r.e.c; ++C) {
          const coord = XLSX.utils.encode_cell({ r: 0, c: C })
          const cell = wb.Sheets['TZ_GXSX'][coord]
          if (cell.v == 'S_POINT') {
            s_poi_c = C
          }
          if (cell.v == 'X') {
            x_c = C
          }
          if (cell.v == 'Y') {
            y_c = C
          }
          if (cell.v == 'E_POINT') {
            // var a1_addr = XLSX.utils.encode_cell({r:0, c:C});
            e_poi_c = C
          }
          if (cell.v == 'X1') {
            x_c_1 = C
          }
          if (cell.v == 'Y1') {
            y_c_1 = C
          }
        }
        // let s_appendCol = XLSX.utils.encode_col(range.e.c + 1);
        for (let R = GXSX_r.s.r + 1; R <= GXSX_r.e.r; ++R) {
          const coord_x = XLSX.utils.encode_cell({ r: R, c: x_c })
          const coord_y = XLSX.utils.encode_cell({ r: R, c: y_c })
          const s_val = XLSX.utils.encode_cell({ r: R, c: s_poi_c })
          const e_val = XLSX.utils.encode_cell({ r: R, c: e_poi_c })
          const coord_x_1 = XLSX.utils.encode_cell({ r: R, c: x_c_1 })
          const coord_y_1 = XLSX.utils.encode_cell({ r: R, c: y_c_1 })
          wb.Sheets['TZ_GXSX'][coord_x] = { t: 'n', f: 'VLOOKUP(' + s_val + ',TZ_GXDSX!A:' + l + ',' + xNum + ',0)' }
          wb.Sheets['TZ_GXSX'][coord_y] = { t: 'n', f: 'VLOOKUP(' + s_val + ',TZ_GXDSX!A:' + l + ',' + yNum + ',0)' }
          wb.Sheets['TZ_GXSX'][coord_x_1] = { t: 'n', f: 'VLOOKUP(' + e_val + ',TZ_GXDSX!A:' + l + ',' + xNum + ',0)' }
          wb.Sheets['TZ_GXSX'][coord_y_1] = { t: 'n', f: 'VLOOKUP(' + e_val + ',TZ_GXDSX!A:' + l + ',' + yNum + ',0)' }
        }
      }

      // let x_col = XLSX.utils.encode_col(x_c),y_col = XLSX.utils.encode_col(y_col)
      // XLSX.utils.sheet_set_array_formula(wb.Sheets['TZ_GXSX'], x_col + "2:" + x_col + GXSX_r.e.r, "VLOOKUP("+ s_poi_col + "2:" + s_poi_col + GXSX_r.e.r +",TZ_GXDSX!A:"+ l + "," + xNum+",0)");
      // XLSX.utils.sheet_set_array_formula(wb.Sheets['TZ_GXSX'], y_col + "2:" + y_col + GXSX_r.e.r, "VLOOKUP("+ s_poi_col + "2:" + s_poi_col + GXSX_r.e.r +",TZ_GXDSX!A:"+ l + "," + yNum+",0)");

      // XLSX.utils.sheet_set_array_formula(wb.Sheets['TZ_GXSX'], x_col_1 + "2:" + x_col_1 + range.e.r, "VLOOKUP("+ e_poi_col + "2:" + e_poi_col + range.e.r +",TZ_GXDSX!A:"+ l + "," + xNum+",0)");
      // XLSX.utils.sheet_set_array_formula(wb.Sheets['TZ_GXSX'], y_col_1 + "2:" + y_col_1 + range.e.r, "VLOOKUP("+ e_poi_col + "2:" + e_poi_col + range.e.r +",TZ_GXDSX!A:"+ l + "," + yNum+",0)");
      if (l && wb.SheetNames.includes('YW_PIPEDEFECTS')) {
        const pipdefects_r = XLSX.utils.decode_range(wb.Sheets['YW_PIPEDEFECTS']['!ref'])
        let pipdefects_x_c, pipdefects_y_c, q_poi_c, z_poi_c, pipdefects_x_c_1, pipdefects_y_c_1
        for (var C = pipdefects_r.s.c; C <= pipdefects_r.e.c; ++C) {
          const coord = XLSX.utils.encode_cell({ r: 0, c: C })
          const cell = wb.Sheets['YW_PIPEDEFECTS'][coord]
          if (cell.v == 'X') {
            pipdefects_x_c = C
          }
          if (cell.v == 'Y') {
            pipdefects_y_c = C
          }
          if (cell.v == 'QSJBH') {
            q_poi_c = C
          }
          if (cell.v == 'X1') {
            pipdefects_x_c_1 = C
          }
          if (cell.v == 'Y1') {
            pipdefects_y_c_1 = C
          }
          if (cell.v == 'ZZJBH') {
            z_poi_c = C
          }
        }
        for (let R = pipdefects_r.s.r + 1; R <= pipdefects_r.e.r; ++R) {
          let pipdefects_x_c, pipdefects_y_c, q_poi_c, z_poi_c, pipdefects_x_c_1, pipdefects_y_c_1
          const coord_x = XLSX.utils.encode_cell({ r: R, c: pipdefects_x_c })
          const coord_y = XLSX.utils.encode_cell({ r: R, c: pipdefects_y_c })
          const s_val = XLSX.utils.encode_cell({ r: R, c: q_poi_c })
          const e_val = XLSX.utils.encode_cell({ r: R, c: z_poi_c })
          const coord_x_1 = XLSX.utils.encode_cell({ r: R, c: pipdefects_x_c_1 })
          const coord_y_1 = XLSX.utils.encode_cell({ r: R, c: pipdefects_y_c_1 })
          wb.Sheets['YW_PIPEDEFECTS'][coord_x] = {
            t: 'n',
            f: 'VLOOKUP(' + s_val + ',TZ_GXDSX!A:' + l + ',' + xNum + ',0)'
          }
          wb.Sheets['YW_PIPEDEFECTS'][coord_y] = {
            t: 'n',
            f: 'VLOOKUP(' + s_val + ',TZ_GXDSX!A:' + l + ',' + yNum + ',0)'
          }
          wb.Sheets['YW_PIPEDEFECTS'][coord_x_1] = {
            t: 'n',
            f: 'VLOOKUP(' + e_val + ',TZ_GXDSX!A:' + l + ',' + xNum + ',0)'
          }
          wb.Sheets['YW_PIPEDEFECTS'][coord_y_1] = {
            t: 'n',
            f: 'VLOOKUP(' + e_val + ',TZ_GXDSX!A:' + l + ',' + yNum + ',0)'
          }
        }
      }

      // XLSX.utils.sheet_set_array_formula(wb.Sheets['YW_PIPEDEFECTS'], pipdefects_xCol + "2:" + pipdefects_xCol + pipdefects_r.e.r, "VLOOKUP("+ q_poi_col + "2:" + q_poi_col + pipdefects_r.e.r +",TZ_GXDSX!A:"+ l + "," + xNum+",0)");
      // XLSX.utils.sheet_set_array_formula(wb.Sheets['YW_PIPEDEFECTS'], pipdefects_yCol + "2:" + pipdefects_yCol + pipdefects_r.e.r, "VLOOKUP("+ q_poi_col + "2:" + q_poi_col + pipdefects_r.e.r +",TZ_GXDSX!A:"+ l + "," + yNum+",0)");
      // XLSX.utils.sheet_set_array_formula(wb.Sheets['YW_PIPEDEFECTS'], pipdefects_zxCol + "2:" + pipdefects_zxCol + pipdefects_r.e.r, "VLOOKUP("+ z_poi_col + "2:" + z_poi_col + pipdefects_r.e.r +",TZ_GXDSX!A:"+ l + "," + xNum+",0)");
      // XLSX.utils.sheet_set_array_formula(wb.Sheets['YW_PIPEDEFECTS'], pipdefects_zyCol + "2:" + pipdefects_zyCol + pipdefects_r.e.r, "VLOOKUP("+ z_poi_col + "2:" + z_poi_col + pipdefects_r.e.r +",TZ_GXDSX!A:"+ l + "," + yNum+",0)");

      // 生成文件并下载
      XLSX.writeFile(wb, this.fileName.substring(0, this.fileName.lastIndexOf('.')) + '属性.xlsx', {
        cellDates: true,
        cellFormula: true
      })
    },
    handleExportTestXls() {
      // 创建工作簿
      const wb = XLSX.utils.book_new()
      this.panes.map((item) => {
        // 将数据写入表格中
        const sheet = XLSX.utils.json_to_sheet(item.testData)
        const range = XLSX.utils.decode_range(sheet['!ref'])
        const firstRow = []
        for (var C = range.s.c; C <= range.e.c; ++C) {
          var coord = XLSX.utils.encode_cell({ r: 0, c: C })
          var cell = sheet[coord]
          if (!cell || !cell.v) continue
          if (cell.v) firstRow.push(cell.v)
          if (cell.v === 'tips') cell.v = '错误字段'
        }
        item.columns.sort((a, b) => {
          return parseInt(a.key) - parseInt(b.key)
        })
        item.columns.map((column) => {
          const idxOf = firstRow.indexOf(column.dataIndex)
          if (idxOf > -1) {
            var coord = XLSX.utils.encode_cell({ r: 0, c: idxOf })
            sheet[coord] = { t: 's', v: column.title }
          }
        })
        // 将工作表放入工作簿中
        XLSX.utils.book_append_sheet(wb, sheet, item.title)
      })
      // 生成文件并下载
      XLSX.writeFile(wb, this.fileName.substring(0, this.fileName.lastIndexOf('.')) + '校验结果.xlsx', {
        cellDates: true,
        cellFormula: true
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.salesCard .ant-tabs-extra-content {
  width: 250px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  color: blue;
}
</style>
